<template>
  <div class="collect">
    <van-sticky>
      <Header title="我的收藏" left-arrow/>
    </van-sticky>
    <div class="collect-outer">
      <div class="collect-container">
        <van-pull-refresh v-model="refreshing" success-text="刷新成功" @refresh="onRefresh">
          <van-list
            v-model="loading"
            :finished="finished"
            :error.sync="error"
            error-text="请求失败，点击重新加载"
            finished-text="没有更多了"
            @load="onLoad"
          >
            <listItem v-for="(item,index) in list" :key="index" :list="item"/>
          </van-list>
        </van-pull-refresh>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import Header from '../../components/Header/NoLeftArrowHeader'
import ListItem from '../../components/ListItem/ListItem'
import { collection } from './../../api/user'
import { Toast } from 'vant'

export default {
  name: 'Collect',
  components: {
    Header,
    ListItem
  },
  data() {
    return {
      loading: false,
      finished: false,
      refreshing: false,
      error: false,
      list: [], // 列表
      page: 1, // 分页
      rows: 10 // 每页条数
    }
  },
  computed: {
    ...mapState({
      id: state => state.user.userInfo.id
    })
  },
  mounted() {
  },
  methods: {
    onRefresh() {
      // 清空列表数据
      this.finished = false
      this.page = 1				// 分页数赋值为1
      this.list = []					// 清空数组
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态

      this.loading = true
      this.onLoad()
    },
    onLoad() {
      this.fetchData()
      this.page++
    },
    async fetchData() {
      if (this.refreshing) {
        this.list = []
        this.refreshing = false
      }

      const { id, page, rows } = this
      const { code, data, msg } = await collection({ id, page, rows })

      if (code === 0) {
        this.list.push(...data.records)
        // 加载状态结束
        this.loading = false
        if (this.error) {
          this.error = false
        }

        // 如果list长度大于等于总数据条数,数据全部加载完成
        if (this.list.length >= data.total) {
          this.finished = true
        }
      } else {
        // 加载状态结束
        this.loading = false
        this.error = true
        this.page = 1
        Toast.fail(msg)
      }
    }
  }
}
</script>

<style scoped lang="less" rel="stylesheet/less">
.collect {
  height: 100%;

  .collect-outer {
    position: fixed;
    top: 46px;
    bottom: 0;
    width: 100%;
    overflow: auto;

    .collect-container {
      height: 100%;

      .van-pull-refresh{
        height: 100%;
        overflow: auto;
      }
    }
  }

}
</style>

<style lang="less">
.van-sticky {
  height: 100%;
}
</style>
